package com.sharemedia.managers.db
{
	import com.sharemedia.events.TrackListEvent;
	import com.sharemedia.interfaces.IDBCommand;
	import com.sharemedia.utils.RatingUtil;
	import com.sharemedia.vos.ServerTrack;
	import com.sharemedia.vos.TrackInfo;
	
	import flash.data.SQLConnection;
	import flash.data.SQLResult;
	import flash.data.SQLStatement;
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.events.IEventDispatcher;
	import flash.events.SQLErrorEvent;
	import flash.events.SQLEvent;
	
	import mx.utils.UIDUtil;
			
	[Event(name="loaded", type="com.sharemedia.events.TrackListEvent")]
	public class LoadTracksCommand  extends EventDispatcher implements IDBCommand
	{
		private const LOAD_TRACKS:String = "SELECT * FROM tracks ORDER BY id";
		
		public function LoadTracksCommand()
		{
			super();
		}
		
		public function execute(connection:SQLConnection):void
		{
			var tracksStat:SQLStatement = new SQLStatement();
			tracksStat.sqlConnection = connection;
			tracksStat.text = LOAD_TRACKS;
			tracksStat.addEventListener(SQLErrorEvent.ERROR, errorHandler);
			tracksStat.addEventListener(SQLEvent.RESULT, loadTracksResult);
			tracksStat.execute();
		}
		
		/**
		 */
		private function errorHandler(e:SQLErrorEvent):void
		{
		}
		
		protected function loadTracksResult(event:Event):void
		{
			var result:SQLResult = event.target.getResult();
			
			var tracks:Array = new Array();
			
			if(result.data)
			{
				for(var i:Number = 0; i < result.data.length; i++)
				{
					var track:ServerTrack = new ServerTrack(result.data[i].uid, result.data[i].fileName, result.data[i].path, result.data[i].likeNum, result.data[i].unlikeNum);
					if(result.data[i].songName || result.data[i].artist)
						track.info = new TrackInfo(result.data[i].songName, result.data[i].artist);
					
					track.length = result.data[i].length;
					tracks.push(track);
					
				}
			}
			
			dispatchEvent(new TrackListEvent(TrackListEvent.LOADED, tracks));
		}
	}
}